package javaweblearn.session;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class BuyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取参数
        String id = req.getParameter("id");
        Books book = DB.getAll().get(id);//获取用户想买的书
        HttpSession session = req.getSession();
        resp.getWriter().print(session);//打印sesson查看内容
        List<Books> list = (List) session.getAttribute("list");  //得到用户用于保存所有书的容器
        if(list==null){
            list = new ArrayList<Books>();
            session.setAttribute("list",list);
        }
        list.add(book);
        //response. encodeRedirectURL(java.lang.String url)用于对sendRedirect方法后的url地址进行重写
        String url = resp.encodeRedirectURL(req.getContextPath()+"/servlet/ListCartServlet");
        System.out.println(url);
        resp.sendRedirect(url);

    }

    @Override
    protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doHead(req, resp);
    }
}
